<?php include_stylesheets_for_form($form) ?>
<?php include_javascripts_for_form($form) ?>
<script type="text/javascript">
// <![CDATA[
var items_q = new Object();//Variable to count how many items of each BOList field are on the form.
var items_config = new Object();//Variable to count how many items of each BOList field are on the form.
var listfields = new Array();//Variable to list which BOList fields are in the form.

function getLabel(fieldName){
	var labels = {
	  <?php
	  $count = 0;
	  foreach($form as $formfield){
			$key = $formfield->renderName();
			$val = $formfield->renderLabelName();
			echo "'". html_entity_decode(htmlentities($key, ENT_QUOTES)) ."':'". html_entity_decode(htmlentities($val, ENT_QUOTES)) ."'". (($form->count() - 1 == $count++) ? '' : ','); 
	  }
	  ?>
	};
	return labels[fieldName];
}
</script>

<?php if(!isset($hide))
	$hide = array(); 
	
	?>
<?php 
$owner_param = '';
if(!empty($owner_id))
{
	$owner_param = '&owner_id=' . $owner_id;
	$ownerData = Util::getOwnerFieldAndClass($form->getObject(), 'List');	
}

if(!isset($buttons)) $buttons=true?>
<?php if(!isset($formAction)){
	if($sf_request->isXmlHttpRequest()){
		$formAction = url_for($module.'/'.($form->getObject()->isNew() ? 'addItem' : 'updateItem').(!$form->getObject()->isNew() ? '?id='.$form->getObject()->getId().'&' : '?').'className='.$className.'&alias='.$alias.$extraParams);
	}
	else
	{
		$formAction = url_for($module.'/'.($form->getObject()->isNew() ? 'create?className='.$className : 'update').(!$form->getObject()->isNew() ? '?id='.$form->getObject()->getId().'&className='.$className : '') . $owner_param.$extraParams);	
	}
}?>
<?php if(!isset($target)){
	$target='';
}else{
	$target = "target=$target";
}?>
<div id="errorDisplayHaut" class="errorDisplay">&nbsp;</div>
<?php 
/* return event.keyCode != 13;
 * prevents form to be submitted with enter key.
 * Combined with the jquery script exected on  .ready
 * add this tag to form
 * onkeypress="return event.keyCode != 13;"
 * */
?>
<form id="Form<?php echo $className ?>" method="post" <?php $form->isMultipart() and print 'enctype="multipart/form-data" ' ?> tmt:validate = "true" tmt:callback="errorOnLabels" class="defaultForm" <?php echo $target;?>>
<?php if (!$form->getObject()->isNew()): ?>
<input type="hidden" name="sf_method" value="put" />
<?php endif; ?>


<?php echo $form->renderGlobalErrors() ?>
<?php if($default=='true'):?>
			<?php  if ($form->isCSRFProtected()) : ?> 
			  <?php echo $form['_csrf_token']; ?> 
			<?php endif; ?>							
			<?php echo $form['id']; ?>
		<?php if(!isset($objDef)) $objDef = new objectDef($className); ?>			
		<?php if($objDef->description): ?>
			<fieldset>
				<legend><?php echo __("General Information"); ?></legend>
		  			<div class="description">
		  				<?php echo $objDef->description?>
		  			</div>
		  	</fieldset>
		<?php endif;?>
		  <?php 
	   	  $section = '';
		  foreach($objDef->attributes as $fieldName => $att):?>
		    <?php if($att['type']!='function'):?>
		        <?php if($section != $att['section'] and $att['show'] and !in_array($fieldName,$form->hiddenFields) ):?>
		        	<?php if($section !=''):?>
		        		</fieldset>
		        	<?php endif;?>
		            <fieldset id="<?php echo Util::stripAccents2($att['section'], true)?>"><legend><?php echo __($att['section'],null,'forms')?></legend>
		            <?php $section = $att['section']?>
		  		<?php endif;?>
			    <?php if($att['type']!='BOList'):?>
		  			<?php echo $objDef->renderAttributeWidget($form, $fieldName, $hide); ?>
			    <?php else:?>
					  <?php if($att['show'] and !in_array($fieldName,$form->hiddenFields)):?>
					  <?php $relatedClass = $att['relatedClass']; $relatedObjDef = new objectDef($relatedClass);?>
					  <div id="wrapper<?php echo $fieldName?>" style="clear: both;">
					  <fieldset><legend><?php echo $att['label']?></legend>
						  <span class="formHint"><?php echo $att['help'] ?> </span>
						   <?php if($att['description']!='') echo $att['description'];?>
						   <br />
						  <a id="add_<?php echo $fieldName?>" class="newItemButton" href="javascript:createItem('<?php echo $fieldName?>');">
							<img src="/images/icons/16/add.png" title="<?php echo __('Create New') . ' ' . $relatedObjDef->label?>"/>
						  </a>
						  
						  <script type="text/javascript">
								items_q['<?php echo $fieldName;?>'] = <?php echo $form[$fieldName]->count()?>;
								listfields.push('<?php echo $fieldName;?>');
						   </script>
						  <div id="list_<?php echo $fieldName?>">
						  	  <table class="items_table">
						  	  <?php $hide = array_keys($relatedObjDef->getAttributesByType('function'));?>
							  <?php echo $relatedObjDef->renderListHeader($hide, 'table', $addActions = true, $width = 0, $addOrderLink = false, $orderFunctionParams = '', $orderField = '', $add = array(), $useShowAtt = true);?>
							  <tbody id="list_body<?php echo $fieldName?>">
							  </tbody>
							  </table>
							  <div id="list_forms<?php echo $fieldName?>" style="display:none">
							  <?php foreach($form[$fieldName] as $key => $subForm):?>
							  	  <div id="form_<?php echo $key?>">
								  <?php include_partial('display/itemForm', array('objDef' => $relatedObjDef, 'form' => $subForm, 'num' => $key, 'ownerFieldname' => $fieldName))?>
								  </div>
							  <?php endforeach;?>
							  </div>
						  </div>
					 </fieldset>
					 </div>
					  <?php endif;?>
				  <?php endif;?> 
		  	<?php endif;?> 	
		  <?php endforeach;?>
		  </fieldset>
		  <div class="buttons">
		  <?php echo link_to('<img title="'.__('Go back').'" src="/images/icons/64/cancel.png"/>', $module.'/index?className='.$className);?>
          <?php if (!$form->getObject()->isNew()): ?>
          	<?php if($objDef->canBeDeleted):?>
            &nbsp;<?php echo link_to('<img title="'.__('Delete').'" src="/images/icons/64/delete.png"/>', $module.'/delete?id='.$form->getObject()->getId().'&className='.$className,  array('method' => 'delete', 'confirm' => __('Are you sure'))); ?>
            <?php endif;?>
          <?php endif; ?>
          <?php if($form->getObject()->etat==1 or $form->getObject()->isNew() or ($form->getObject()->public and $form->getObject()->created_by_id == $sf_user->getUserProfile()->id)):?>
          	 <?php if($form->getObject()->etat==1 or $form->getObject()->isNew()):?>
		          <button id="saveButton" formaction="<?php echo $formAction ?>" formmethod="post" <?php if($form->isMultipart()) print 'formenctype="multipart/form-data" ' ?>>
		          <img alt="Save" title="Enregistrer en Brouillon" src="/images/icons/64/draft.png">
		          </button>
	         <?php endif?>
	          <button id="saveAndSendButton" formaction="<?php echo url_for('messages/saveAndSend'. ($form->getObject()->isNew() ? '' : '?id='.$form->getObject()->getId())) ?>" formmethod="post" <?php if($form->isMultipart()) print 'formenctype="multipart/form-data" ' ?>>
	          	<img src="/images/icons/64/sendmessage.png" title="<?php echo __('Envoyer le message')?>">
	          </button>
          <?php endif;?>
		  </div>
		  
<?php endif;?>

<?php 
if(isset($form->extraTemplates)){
	if(is_array($form->extraTemplates)){
		foreach($form->extraTemplates as $template){
			include_partial($template, array('form'=>$form)); 
		}
	}
}
// include_partial('sendnotifications', array('self'=>$form->getObject(), 'objDef' => $objDef));
?>
</form>

<!-- Mock forms -->
<?php foreach($objDef->attributes as $fieldName => $att):?>
<?php if($att['type']=='BOList'):?>
	 <?php if($att['show'] and !in_array($fieldName,$form->hiddenFields)):?>
		<?php $relatedClass = $att['relatedClass']; 
			  $relatedObjDef = new objectDef($relatedClass);
			  $formClass = $relatedClass . 'Form';
		      $subForm = new $formClass();?>
			  <script type="text/javascript">
			    var cfgFieldName = '<?php echo $fieldName?>';
			  	var cfg = new Object();
			  <?php foreach($relatedObjDef->attributes as $relatedFieldName => $relatedAtt):?>
			  <?php  if($relatedAtt['type']=='BO' or $relatedAtt['type']=='BOList'){ $relatedFieldName2 = $relatedFieldName . '_id';}else{$relatedFieldName2 = $relatedFieldName;}
				if($relatedAtt['type']=='function' or $relatedAtt['show']==false){ $visible = 0; } else { $visible = 1;} ?>
			    var relatedFieldName = '<?php echo $relatedFieldName2?>';
			    cfg[relatedFieldName] = { visible : <?php echo $visible?>, name : '<?php echo $relatedFieldName2;?>'
				};
			  <?php endforeach;?>
			   cfg['label'] = '<?php echo html_entity_decode(htmlentities($relatedObjDef->label, ENT_QUOTES))?>';
			   cfg['canBeDeleted'] = '<?php echo $relatedObjDef->canBeDeleted?>';
			   items_config[cfgFieldName] = cfg;
		      </script>
		<div id="container_mock_form_<?php echo $fieldName?>" class="mockForm">
			<form id="mock_form_<?php echo $fieldName ?>" action="#" tmt:validate = "true" tmt:callback="errorOnLabels" class="subForm" >
			  <input type="hidden" id="index" value=""/>
			  <input type="hidden" id="itemClassname" value="<?php echo $relatedClass?>"/>
			  <?php include_partial('display/itemForm', array('objDef' => $relatedObjDef, 'form' => $subForm, 'num' => 'mock', 'ownerFieldname' => $fieldName, 'owner_id' => $owner_id, 'module' => $module))?>
			</form>
		</div>
	 <?php endif;?>			  
<?php endif;?>
<?php endforeach;?>

<script type="text/javascript">
	
	$(document).ready(function() {
		for(i = 0;i < listfields.length; i++)
		{
			refreshItemList(listfields[i]);
		}

	
        $( ".mockForm" ).dialog({ autoOpen: false , modal: true,
								  minWidth: 700,
								  dialogClass: 'mockForm',
								  title: __('Edit Item')
            					 });
        						// buttons: { Ok: function() { $( this ).dialog( "close" ); } } });
    
	});

	function HandleKeyPress(e) {
	    switch (e.keyCode) {
	        case e.DOM_VK_ENTER:
	    	if (e.preventDefault)
	    	    e.preventDefault();
		else e.returnValue = false;
	    }
	}
	
	function createItem(fieldname) {
		num = items_q[fieldname];
		var xhr = getXmlHttpRequest2();
		xhr.open("POST","<?php print url_for($module.'/addItem'); ?>",false);
		xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		xhr.setRequestHeader('X_REQUESTED_WITH','XMLHttpRequest');
		var id = <?php echo ($form->getObject()->isNew()?'0':$form->getObject()->getId())?>;
		xhr.send('id=' + id + '&num=' +num + '&fieldname=' + fieldname + '&ownerclass=<?php echo $objDef->className ?>' );
		var idDiv = 'list_' + fieldname;
		var newDiv = document.createElement('div');
		newDiv.innerHTML = xhr.responseText;
		newDiv.setAttribute('id', 'form_' + items_q[fieldname]);
		newDiv.setAttribute('style', 'display:none;');
		document.getElementById(idDiv).appendChild(newDiv);
		var index = items_q[fieldname];
	    items_q[fieldname] = items_q[fieldname] + 1;
	    showDialog(fieldname, index);
	   
	}

	function deleteItem(fieldname, idFormDiv) {
		<?php //TODO Ask for confirmation ?>
		if (confirm('<?php echo __('Are you sure?')?>'))
		{
			document.getElementById(idFormDiv).innerHTML = '';
			refreshItemList(fieldname);
		}
	}


	function showDialog(fieldname, index)
	 {
		//center(document.getElementById(divname));
		var subForm = document.getElementById('mock_form_' +  fieldname);
		if(subForm)
		{
			subForm.index.value = index;
			var itemClassname = subForm.itemClassname.value ;
			var form_id = 'Form<?php echo $className ?>';
			var prefix = '<?php echo $className ?>_' + fieldname + '_' + index;
			var mainForm = document.forms[form_id];
			for (var i=0;i<mainForm.length;i++)
			{
				var input = mainForm.elements[i];
				var inputId = input.id;
				if(is_item_subform(prefix, inputId))
				{
					var formFieldId = itemClassname + inputId.replace(prefix,'');
					for(var j = 0; j< subForm.length; j++)
					{
						if(subForm.elements[j].id == formFieldId)
						{ 
							if(subForm.elements[j].type ==	'checkbox')
							{
								subForm.elements[j].checked = input.checked ;
							}
							else
							{
								subForm.elements[j].value = input.value;
							}
							
						}
					}
				}
			}

			divname = '#container_mock_form_' +  fieldname;
			var title = __('Edit') + ' ' + items_config[fieldname].label;
			$(divname).dialog('option', 'title', title);
			$(divname).dialog('open');

		}
	 }

	function closeSubForm(fieldname)
	{
		var subForm = document.getElementById('mock_form_' +  fieldname);
		var index = subForm.index.value;
		var itemClassname = subForm.itemClassname.value ;

		var form_id = 'Form<?php echo $className ?>';
		var prefix = '<?php echo $className ?>_' + fieldname + '_' + index;
		
		if(subForm)
		{
			if(tmt.validator.validateForm(subForm))
			{
				mainForm = document.forms[form_id];
				for (var i=0;i<mainForm.length;i++)
				{
					var input = mainForm.elements[i];
					var inputId = input.id;
					if(is_item_subform(prefix, inputId))
					{
						var formFieldId = itemClassname + inputId.replace(prefix,'');
						for(var j = 0; j< subForm.length; j++)
						{
							if(subForm.elements[j].id == formFieldId)
							{ 
								if(subForm.elements[j].type == 'file')
								{
									var xid = input.id;
									var xname = input.name;
									input = subForm.elements[j].cloneNode(1);
									input.id = xid;
									input.name = xname;
									//input.files = subForm.elements[j].files ;
								}
								else if(subForm.elements[j].type ==	'checkbox')
								{
									input.checked = subForm.elements[j].checked ;
								}
								else
								{
									input.value = subForm.elements[j].value ;
								}
							}
						}
					}
				}				
				divname = '#container_mock_form_' +  fieldname;
				$(divname).dialog('close');
				refreshItemList(fieldname);
			}
		}
		//tmt.validator.validateFields(fields[], [callback])
	}

	function cleanDiv(div)
	{
		 while (div.childNodes.length != 0)
			 div.removeChild(div.childNodes[0]);
		
			
	}
	
	function refreshItemList(fieldname)
	{	
		var form_id = 'Form<?php echo $className ?>';
		var prefix = '<?php echo $className ?>_' + fieldname;
		oFormObject = document.forms[form_id];
		html = '';
		var idDiv = 'list_body' + fieldname;
		var container = document.getElementById(idDiv);
		//if(container.textContent !='') container.textContent = '';
		cleanDiv(container);
		var index = '';
		var canBeDeleted = items_config[fieldname].canBeDeleted;
		for (var i=0;i<oFormObject.length;i++)
		{
			var input = oFormObject.elements[i];
			var inputId = input.id;
			if(is_item_subform(prefix, inputId))
			{
				var suffix = inputId.substring(prefix.length + 1);
				var value  = getInputValue(input);
				n = suffix.indexOf('_');
				var item_index = suffix.substring(0,n);
				var itemFieldname = suffix.substring(n + 1);
				if(itemFieldname=='id')
				{	
					if(value=='')
					{
						canBeDeleted=true;
					}
					else
					{
						var canBeDeleted = items_config[fieldname].canBeDeleted;
					}
				}
				if(input.type!='hidden')
				{
					if(index != item_index)
					{
						//it's a new row
						var rowDiv = document.createElement('tr');
						rowDiv.setAttribute('class','list_row');
						rowDiv.setAttribute('className','list_row');
						container.appendChild(rowDiv);
						var span = document.createElement('td');
						span.setAttribute('class','list_cell');
						span.setAttribute('className','list_cell');
						var link = document.createElement('a');
						link.setAttribute('href', "javascript:void(0);");
						link.setAttribute('href', 'javascript:showDialog("' + fieldname + '", ' + item_index + ');');
						//link.setAttribute('onclick', 'showDialog("' + fieldname + '", ' + item_index + ');');
						link.setAttribute('class','itemscontrolButton' + fieldname);
						link.setAttribute('className','itemscontrolButton' + fieldname);
						var img = document.createElement('img');
						img.setAttribute('src', "/images/icons/16/edit.png");
						//img.setAttribute('class','itemscontrolButton' + fieldname);
						//img.setAttribute('className','itemscontrolButton' + fieldname);
						link.appendChild(img);
						span.appendChild(link);
						if(canBeDeleted)
						{
							var link = document.createElement('a');
							//link.setAttribute('href', "#div_" + fieldname + "_" + item_index + "_Form");
							link.setAttribute('href', "javascript:void(0);");
							link.setAttribute('href', 'javascript:deleteItem("' + fieldname +'", "div_' + fieldname + '_' + item_index + '_Form");');
							//link.setAttribute('onclick', '$("#div_' + fieldname + '_' + item_index + '_Form").show();');
							//link.setAttribute('onclick', 'deleteItem("' + fieldname +'", "div_' + fieldname + '_' + item_index + '_Form");');
							link.setAttribute('class','itemscontrolButton' + fieldname);
							link.setAttribute('className','itemscontrolButton' + fieldname);
							var img = document.createElement('img');
							img.setAttribute('src', "/images/icons/16/delete.png");
							link.appendChild(img);
							span.appendChild(link);
						}
						rowDiv.appendChild(span);
					}
					if(items_config[fieldname][itemFieldname].visible)
					{
						var span = document.createElement('td');
						span.setAttribute('class','list_cell');
						span.setAttribute('className','list_cell');
						span.innerHTML = value;
						rowDiv.appendChild(span);
					}
					index = item_index;
				}		
						
				// html = html + inputId + '=' + value + '<br />';
				
			}
			
		}
				
		//$("a.itemscontrolButton" + fieldname).fancybox({
		//	'showCloseButton' : false,
		//	'width'			  : 600,
		//	'autoDimensions'  : false,
		//	'onClosed'        : function(){refreshItemList(fieldname);}
		//});
		
		
			
	}

	function is_item_subform(prefix, inputId) {
		var count = prefix.length;
	    if (prefix === inputId.substring(0, count)) {
	           return true;
	    }
	    return false;
	}
	
	function getInputValue(input)
	{
		switch(input.type)
		{
		case 'checkbox':
		   if(input.checked)
		   {
				return 'Oui';
		   }
		   else
		   {
				return 'Non';
		   }
		  break;
		case 'select-one':
		  return input.options[input.selectedIndex].text;
		  break;
		default:
		  return input.value;
		}
		
		
	}

	function customVal(validators, formNode){
		if(formNode.id=='Formmessage'){
			if(! document.getElementById("message_public").checked){
				var roles = $("[id^='message_roles_list']:checked");
				if(roles.length==0 && items_q['destinataires'] == 0){
					x = validators.length;
					validators.push(tmt.validator.fieldValidatorFactory(document.getElementById("message_id")));
					validators[x].message = "Vous n'avez pas choisi des destinataires pour votre message.";
					document.getElementById("notifroles").innerHTML = "Vous n'avez pas choisi des destinataires pour votre message";
					document.getElementById("notifroles").style = "color: red;";
				}else{
					document.getElementById("notifroles").innerHTML = "";
				}
			}
			if(document.getElementById("message_contenu").value == '' && document.getElementById("message_header").value == ''){
				x = validators.length;
				validators.push(tmt.validator.fieldValidatorFactory(document.getElementById("message_header")));
				validators[x].message = "Veuillez definir un contenu à votre message. Vous devez saisir l'entête ou le contenu";
			} 
			
		}
	} 
	
</script>



	<?php if($objDef->hasAttach):?>
		<?php include_partial('attachments/addFilesToForm', array( 'form' => $formAttach)) ?>
	<?php endif;?>
	
